package com.example.demo.filter;

import com.example.demo.util.TraceIdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * HTTP 方法过滤器
 * 限制只允许 GET 和 POST 请求
 * 
 * @author zhang
 * @date 2024
 */
@Component
public class HttpMethodFilter implements Filter {
    
    private static final Logger logger = LoggerFactory.getLogger(HttpMethodFilter.class);
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        // 生成TraceId并设置到线程上下文（在过滤器层面确保所有请求都有TraceId）
        String traceId = TraceIdUtil.generateTraceId();
        TraceIdUtil.setTraceId(traceId);
        
        // 在响应头中添加TraceId
        httpResponse.setHeader("X-Trace-Id", traceId);
        
        String method = httpRequest.getMethod();
        
        try {
            // 只允许 GET 和 POST 请求
            if (!"GET".equals(method) && !"POST".equals(method)) {
                logger.warn("拒绝的 HTTP 方法: {} from {}", method, httpRequest.getRequestURI());
                httpResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                httpResponse.getWriter().write("{\"code\":405,\"message\":\"只允许 GET 和 POST 请求\"}");
                httpResponse.setContentType("application/json;charset=UTF-8");
                return;
            }
            
            chain.doFilter(request, response);
        } finally {
            // 在过滤器链完成后清除TraceId
            TraceIdUtil.removeTraceId();
        }
    }
}

